package com.cosmos.codegen.base.engine;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cosmos.codegen.base.db.DB;
import com.cosmos.codegen.base.db.DBStaticFactory;
import com.cosmos.codegen.base.domain.DBTypeMapper;
import com.cosmos.codegen.base.domain.TableRelationDomain;
import com.cosmos.codegen.base.domain.TemplateDomain;
import com.cosmos.codegen.utils.DateUtil;

public class ORACLEFreeMarikerEngine extends FreeMarkerEngine {

	@Override
	public List<TemplateDomain> generateTableEntity(TableRelationDomain trd) {
		List<TemplateDomain> tdList = new ArrayList<TemplateDomain>();
		DB db = DBStaticFactory.getDB("oracle");
		Connection connection = null;
		try {
			connection = db.getConnection();
			String[] tablesName = trd.getTablesName();
			for(int i = 0; i < tablesName.length; i++) {
				
				TemplateDomain root = new TemplateDomain();
				
				ResultSet executeQuery = connection.createStatement().executeQuery("select * from " + tablesName[i]);
				ResultSetMetaData metaData = (ResultSetMetaData) executeQuery.getMetaData();

				root.setTableName(tablesName[i].toLowerCase());
				root.setDate(DateUtil.getFormatTime(DateUtil.FORMAT_1));
				root.setVersion("1.0");
				
				root.setPackageName("com.cosmos.domain");
				root.setClassName(getClassName(tablesName[i], trd.getPrefix()));
				
				
				int columnCount = metaData.getColumnCount();
				Map<String, String> columnsInfoMap = new HashMap<String, String>();
				for(int j = 1; j <= columnCount; j++) {
					columnsInfoMap.put(handleSpecialCharacter(metaData.getColumnName(j)), DBTypeMapper.TYPE_MAPPER.get(metaData.getColumnTypeName(j)));
				}
				root.setRoot(columnsInfoMap);
				
				tdList.add(root);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			db.closeConnection(connection);
		}
		
		return tdList;
	}

}
